<!--
 * @Author: xuna
 * @Descripttion: 新增编辑公告资讯
-->
<template>
  <div class="detail-panel">
    <el-drawer
      v-if="isOpenDetail"
      :title="drawerTitle"
      :visible.sync="isOpenDetail"
      :wrapper-closable="false"
      :direction="direction"
      size="40%"
      :before-close="beforeClose"
      class="draw-panel"
    >
      <div v-loading="loading" class="detail-wrap">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="公告标题:" prop="title">
            <el-input v-model="ruleForm.title"></el-input>
          </el-form-item>
          <el-form-item label="公告内容:" prop="content" class="notice-cont">
            <el-input
              v-model="ruleForm.content"
              type="textarea"
              resize="none"
              placeholder="请输入公告内容"
              maxlength="3000"
              show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item label="类型:" prop="type">
            <el-checkbox-group v-model="ruleForm.type" @change="ladderChange">
              <el-checkbox
                v-for="item in typeList"
                :key="item"
                :label="item"
                name="type"
              ></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.type == '图片'"
            label="上传图片:"
            prop="imgList"
            class="type-row"
          >
            <div class="picture">
              <div class="img-list">
                <draggable
                  v-model="ruleForm.imgList"
                  group="people"
                  @start="drag = true"
                  @end="drag = false"
                >
                  <div v-for="(v, index) in ruleForm.imgList" :key="index" class="img-con">
                    <img
                      src="@/assets/img/icon_delete_x.png"
                      class="delete-icon"
                      @click="deleteImg(index)"
                    />
                    <img class="show-img" :src="v" />
                  </div>
                  <div v-show="ruleForm.imgList.length < 9" class="btn-upload">
                    <span>+</span>
                    <input ref="uploadWidgetImg" type="file" @change="handleImage" />
                  </div>
                </draggable>
              </div>
            </div>
            <div class="tips">
              最多上传9张图片，支持png/bmp/jpg/gif格式，大小不超
              过5M上传图片后，您可拖动图片进行图片排序。
            </div>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.type == '视频'"
            label="上传视频:"
            prop="videoPath"
            class="type-row"
          >
            <div class="uploadArea" @click="doUpload(false)">
              <input v-show="false" id ref="uploadWidget" required type="file" name />
              <div v-if="!ruleForm.videoPath">
                <span>+</span>
              </div>
              <div v-else style="width:100%;height:100%">
                <video
                  style="width:100%;height:100%"
                  :src="ruleForm.videoPath"
                  muted
                  controls
                  playsinline
                  x5-video-player-type="h5"
                  name="media"
                  data-video="0"
                ></video>
              </div>
              <!-- <el-progress
                v-if="isShowGress"
                style="width:300px"
                :text-inside="true"
                :stroke-width="15"
                :percentage="percentComplete"
              ></el-progress> -->
            </div>
            <p v-if="ruleForm.videoPath" class="upload-tip" @click="doUpload(true)">重新上传</p>
            <div class="tips">
              建议上传16：9，分辨率1280*720及以上视频
              限制上传最长5分钟时长，不超过100M的mp4格式视频文件。
            </div>
          </el-form-item>
          <el-form-item label="是否允许分享:" prop="isShare" label-width="80">
            <el-switch v-model="ruleForm.isShare"></el-switch>
          </el-form-item>
          <el-form-item label="是否发布:" prop="status" class="status-info">
            <el-switch v-model="ruleForm.status"></el-switch>
          </el-form-item>
          <el-form-item class="status-tip">
            开启之后，企业员工将会在薪福利-公告资讯中看到该文章
          </el-form-item>
          <el-form-item class="submit-btn">
            <el-button @click="resetForm('ruleForm')">取消</el-button>
            <el-button type="primary" @click="submitForm('ruleForm')">保存并提交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
    <el-drawer
      :title="loadTitle"
      :visible="isVisible"
      direction="rtl"
      size="40%"
      :before-close="loadhandleClose"
      class="upload-panel"
      :wrapper-closable="false"
    >
      <Uploader
        ref="mychild"
        :is-visible.sync="isVisible"
        :edit-data="editData"
        @formData="formData"
        @getVideoInfo="getVideoInfo"
      />
    </el-drawer>
  </div>
</template>

<script>
  // uploadVideo
  import { saveAndUpdate, batchUploadImage, getNotice } from '@/api/noticeinformation';
  import draggable from 'vuedraggable';
  import Uploader from '@/components/Uploader/Uploader';
  import { mapGetters } from 'vuex';
  export default {
    components: {
      draggable,
      Uploader,
    },
    props: {
      noticeRow: {
        type: Object,
        default() {
          return {};
        },
      },
      isOpenDetail: {
        type: Boolean,
        required: true,
      },
      isEdit: {
        type: Boolean,
        required: true,
      },
    },
    data() {
      return {
        direction: 'rtl',
        drawerTitle: '新增公告资讯',
        typeList: ['文本', '图片', '视频'],
        isShowGress: false,
        loading: false,
        ruleForm: {
          title: '',
          content: '',
          isShare: false,
          status: false,
          type: [],
          imgList: [],
          videoPath: '',
        },
        rules: {
          title: [
            { required: true, message: '请输入公告标题', trigger: 'blur' },
            { min: 0, max: 50, message: '长度在 0 到 50 个字符', trigger: 'blur' },
          ],
          content: [
            { required: true, message: '请输入公告内容', trigger: 'blur' },
            { min: 0, max: 3000, message: '长度在 0 到 3000 个字符', trigger: 'blur' },
          ],
          isShare: [{ required: true }],
          status: [{ required: true }],
          type: [{ type: 'array', required: true, message: '请选择公告类型', trigger: 'change' }],
          imgList: [{ type: 'array', required: true, message: '请上传图片', trigger: 'change' }],
          videoPath: [{ required: true, message: '请上传视频', trigger: 'change' }],
        },
        percentComplete: 0,
        duration: null, //视频时长
        isVisible: false,
        editData: null,
        loadTitle: '上传素材',
      };
    },
    computed: {
      ...mapGetters('user', ['userInfo']),
      isClient() {
        return !!this.userInfo.isClient || false;
      },
    },
    watch: {
      noticeRow(newDtat) {
        if (newDtat) {
          this.initNotice(newDtat && this.isEdit);
        }
      },
    },

    activated() {},
    methods: {
      initNotice(val) {
        if (val) {
          this.loading = true;
          this.drawerTitle = '编辑公告资讯';
          try {
            getNotice(this.noticeRow.id).then(res => {
              this.loading = false;
              if (res.status == 200) {
                console.log(res);
                let ruleForm = JSON.parse(JSON.stringify(res.data));
                this.ruleForm = {
                  ...ruleForm,
                  isShare: Boolean(ruleForm.isShare),
                  status: Boolean(ruleForm.status),
                  type: ruleForm.type == 1 ? ['文本'] : ruleForm.type == 2 ? ['图片'] : ['视频'],
                  imgList:
                    ruleForm.filePath && ruleForm.type == 2 ? ruleForm.filePath.split(',') : [],
                  videoPath: ruleForm.filePath && ruleForm.type == 3 ? ruleForm.filePath : '',
                };
                console.log(this.ruleForm, '-------------eee---');
              }
            });
          } catch (error) {
            this.loading = false;
          }
        } else {
          this.drawerTitle = '新增公告资讯';
          this.ruleForm = {
            title: '',
            content: '',
            isShare: false,
            status: false,
            type: [],
            imgList: [],
            videoPath: null,
          };
        }
      },
      beforeClose() {
        this.$emit('closeDrawer', false);
      },
      ladderChange() {
        if (this.ruleForm.type.length > 1) {
          this.ruleForm.type.shift();
          console.log(this.ruleForm.type);
        }
      },
      deleteImg(index) {
        this.ruleForm.imgList.splice(index, 1);
      },
      handleImage() {
        const _this = event.target;
        const file = _this.files[0];
        console.log(file, '---------');
        if (!/(jpg|png|bmp|jpeg|gif)$/.test(file.name.toLowerCase())) {
          this.$message.error('请上传jpg、png、bmp或gif格式的图片');
          _this.value = '';
          return;
        }
        if (file.size > 5 * 1024 * 1024) {
          this.$message.error('上传图片不能大于5M');
          _this.value = '';
          return;
        }
        const fileReader = new FileReader();
        fileReader.readAsDataURL(file);
        fileReader.onload = async () => {
          // const blob = this.dataURLtoBlob(e.target.result);
          // let resultData = e.target.result;
          let _flie = file;
          if (this.isClient) {
            const { electronReadFile } = require('@/utils/electronUpload');
            _flie = await electronReadFile(_flie.path);
          }
          let formData = new FormData();
          formData.append('files', _flie);
          try {
            batchUploadImage(formData).then(res => {
              if (res.status == 200) {
                console.log(res);
                this.ruleForm.imgList.push(res.data[0].filePath);
                this.$refs.uploadWidgetImg.value = '';
              } else {
                this.$refs.uploadWidgetImg.value = '';
                return this.$message.error('上传失败！');
              }
            });
          } catch (error) {
            this.$refs.uploadWidgetImg.value = '';
          }
        };
      },
      dataURLtoBlob(dataurl) {
        var arr = dataurl.split(','),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], { type: mime });
      },
      doUpload(val) {
        // 视频组件上传
        if (val) {
          this.editData = { id: this.ruleForm.videoId };
        } else {
          this.editData = null;
        }
        this.isVisible = true;
        // this.$refs.uploadWidget.click();
      },
      // uploadvideo() {
      //   // 上传视频
      //   let inputDOM = event.target;
      //   let file = inputDOM.files[0];
      //   if (inputDOM.files[0] === undefined) {
      //     // this.$message.error('上传失败');
      //     return;
      //   } else {
      //     let videoType = ['video/mp4'];
      //     if (videoType.indexOf(file.type) < 0) {
      //       this.$message.error('请正确上传视频格式');
      //       return;
      //     }
      //     this.fileSize = file.size;
      //     let fileSize = (this.fileSize / 1024 / 1024).toFixed(2);
      //     if (fileSize > 100) {
      //       return this.$message.error('上传视频大小超过100M限制！');
      //     }
      //     this.ruleForm.videoPath = '';
      //     var videoUrl = URL.createObjectURL(file);
      //     var videoObj = document.createElement('video');
      //     videoObj.src = videoUrl;
      //     let _this = this;
      //     videoObj.addEventListener('loadedmetadata', function() {
      //       _this.duration = videoObj.duration;
      //       console.log('-----------视频时长', _this.duration);
      //       if (_this.duration > 5 * 60) {
      //         return this.$message.error('限制上传视频最长5分钟时长！');
      //       }
      //       _this.getOOSUploadVIdeoUrl(file);
      //     });
      //   }
      // },
      // getOOSUploadVIdeoUrl(file) {
      //   const formdata = new FormData();
      //   formdata.append('file', file);
      //   this.isShowGress = true;
      //   let config = {
      //     onUploadProgress: progressEvent => {
      //       let complete = ((progressEvent.loaded / progressEvent.total) * 100) | 0;
      //       this.percentComplete = complete;
      //     },
      //   };
      //   uploadVideo(formdata, config).then(res => {
      //     if (res.status == 200) {
      //       console.log(res);
      //       this.isShowGress = false;
      //       this.percentComplete = 0;
      //       this.$refs.uploadWidget.value = '';
      //       this.ruleForm.videoPath = res.data.filePath;
      //     } else {
      //       return this.$message.error('上传失败！');
      //     }
      //   });
      // },

      submitForm(formName) {
        this.$refs[formName].validate(valid => {
          console.log(formName);
          if (valid) {
            this.loading = true;
            console.log(this.ruleForm);
            let noticeType =
              this.ruleForm.type[0] == '文本' ? 1 : this.ruleForm.type[0] == '图片' ? 2 : 3;
            let ruleForm = {
              ...this.ruleForm,
              type: noticeType,
              isShare: Number(this.ruleForm.isShare),
              status: Number(this.ruleForm.status),
            };
            if (this.ruleForm.imgList && this.ruleForm.imgList.length && noticeType == 2) {
              let filePath = this.ruleForm.imgList.join(',');
              console.log(filePath);
              ruleForm = Object.assign(ruleForm, { filePath });
            }
            if (this.ruleForm.videoPath && noticeType == 3) {
              ruleForm = Object.assign(ruleForm, { filePath: this.ruleForm.videoPath });
            }
            if (this.isEdit) {
              ruleForm = Object.assign(ruleForm, { version: this.noticeRow.version });
            }
            console.log(ruleForm);
            try {
              saveAndUpdate(ruleForm).then(res => {
                this.loading = false;
                if (res.status == 200) {
                  this.$emit('successEdit', false);
                  this.$refs.ruleForm.resetFields();
                  this.$message({
                    type: 'success',
                    message: '新建成功!',
                  });
                }
              });
            } catch (error) {
              this.loading = false;
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$emit('closeDrawer', false);
        if (this.drawerTitle.includes('编辑')) return;
        this.$refs[formName].resetFields();
      },
      loadhandleClose() {
        this.isVisible = false;
        this.editData = null;
      },
      // 获取表单里面的数据
      formData(values) {
        this.isVisible = values;
      },
      getVideoInfo(val) {
        this.ruleForm = Object.assign(this.ruleForm, {
          videoId: val.videoId,
          videoPath: val.videoPath,
          smallPicPath: val.smallPicPath,
        });
      },
    },
  };
</script>

<style lang="scss" scoped>
  @import '~@/styles/mixin.scss';

  .demo-ruleForm {
    // height: 100%;
    overflow: auto;
    .upload-tip {
      @include font(14px, #3770eb, 800);
      margin-top: 12px;
      cursor: pointer;
    }
  }
  .upload-panel {
    /deep/.el-drawer__body {
      padding: 16px 10px 0 10px !important;
    }
    /deep/.el-textarea,
    /deep/.el-select--medium {
      width: auto !important;
    }
  }
  .detail-panel {
    /deep/.el-drawer {
      border-radius: 14px 0 0 14px;
    }
    /deep/.el-drawer__header {
      display: flex;
      align-items: center;
      @include font(16px, #34363b, bold);
      height: 60px;
      background: rgba(255, 255, 255, 1);
      box-shadow: 0px 1px 12px 0px rgba(194, 194, 198, 0.31);
      padding: 0 0 0 14px;
    }
    /deep/.el-drawer__body {
      padding: 16px 28px 0 37px;
      box-sizing: border-box;
      overflow-y: auto;
    }
    .notice-cont {
      /deep/.el-textarea__inner {
        min-height: 234px !important;
        background-color: #f7f6f9;
        border-radius: 7px;
        border: 0 none;
        padding: 10px;
        box-sizing: border-box;
      }
      /deep/.el-input__count {
        background-color: #f7f6f9;
        @include font(10px, #b4b8be, 400);
      }
    }

    /deep/.el-checkbox__input.is-checked .el-checkbox__inner {
      border-radius: 50%;
      background-color: #3770eb;
      border-color: #3770eb;
    }
    /deep/.el-checkbox__inner {
      border-radius: 50%;
    }

    .status-info {
      margin-bottom: 0px;
    }
    .status-tip {
      @include font(14px, #7f848b, 400);
    }
    .submit-btn {
      display: flex;
      justify-content: flex-end;
      margin-top: 20px;
    }
    .type-row {
      display: flex;
      /deep/.el-form-item__label {
        width: 160px !important;
      }
      /deep/.el-form-item__content {
        display: flex;
        flex-direction: column;
        margin-left: 0 !important;
      }
      .tips {
        @include font(14px, #7f848b, 400);
      }
      .picture {
        display: flex;
      }
      .img-list {
        display: flex;
        > div {
          display: flex;
          flex-wrap: wrap;
        }
        .img-con {
          position: relative;
          @include wh(118px, 76px);
          margin: 0 0 16px 16px;
          .show-img {
            @include wh(100%, 100%);
            border-radius: 7px;
          }
          .delete-icon {
            @include wh(16px, 16px);
            position: absolute;
            top: -8px;
            right: -8px;
          }
        }
      }
      .uploadArea {
        @include wh(222px, 114px);
        background-color: #f7f6f9;
        border-radius: 7px;
        display: flex;
        align-items: center;
        justify-content: center;
        @include font(13px, #cacacc, 500);
      }
    }
  }
  .btn-upload {
    @include wh(118px, 76px);
    background-color: #f3f3f3;
    border-radius: 7px;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 16px;
    span {
      @include font(14px, #ccc, 400);
    }
    input[type='file'] {
      position: absolute;
      top: 0px;
      left: 0px;
      height: 100%;
      width: 100%;
      outline: none;
      z-index: 99;
      opacity: 0;
    }
  }
</style>
